package com.trex.modules.tbl.web;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.trex.modules.tbl.checkman.entity.TblZdJcr;
import com.trex.modules.tbl.checkman.service.TblZdJcrService;
import com.trex.modules.tbl.entity.ServerTrexConfig;
import com.trex.modules.tbl.lineform.entity.TblXdZxxdctzd;
import com.trex.modules.tbl.lineform.service.TblXdZxxdctzdService;
import com.trex.modules.tbl.replyform.entity.TblXdJxchsd;
import com.trex.modules.tbl.workerplace.dao.TblZdWorkerdzDao;
import com.trex.modules.tbl.workerplace.entity.TblZdWorkerdz;
import com.trex.modules.utils.JsonGenerator;
import com.trex.modules.utils.JsonToMapParser;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.http.HttpClientUtils;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.trex.modules.tbl.dw.entity.TblDwPro;
import com.trex.modules.tbl.dw.service.TblDwProService;
import com.trex.modules.tbl.entity.TblXdLjzyjl;
import com.trex.modules.tbl.entity.impl.MainModel;
import com.trex.modules.tbl.entity.impl.SecondModel;
import com.trex.modules.tbl.entity.impl.SysinfoModel;
import com.trex.modules.tbl.service.TblXdLjzyjlService;
import com.trex.modules.utils.TimeUtils;

import static com.trex.modules.utils.JsonGeneratorDetail.createJson;
import static com.trex.modules.utils.JsonSenderUtil.sendJsonWithHttpClient;
import static java.lang.Thread.sleep;

/**
 * 列检作业记录Controller
 * @author jy
 * @version 2022-08-29
 */
@Controller
@RequestMapping(value = "/tbl/tblXdLjzyjl")
public class TblXdLjzyjlController extends BaseController {

	@Autowired
	private TblXdLjzyjlService tblXdLjzyjlService;
	@Autowired
	private TblDwProService tblDwProService;
	@Resource
	private AmqpTemplate amqpTemplate;
	@Autowired
	private TblZdWorkerdzDao tblZdWorkerdzDao;
	@Autowired
	private TblZdJcrService tblZdJcrService;
	@Autowired
	private TblXdZxxdctzdService tblXdZxxdctzdService;




	private final ServerTrexConfig serverTrexConfig;

    public TblXdLjzyjlController(ServerTrexConfig serverTrexConfig) {
        this.serverTrexConfig = serverTrexConfig;
    }


    /**
	 * 获取数据
	 */
	@ModelAttribute
	public TblXdLjzyjl get(String recId, boolean isNewRecord) {
		return tblXdLjzyjlService.get(recId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:view")
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(value = "userid", required = false) String userid,
					   @RequestParam(value = "postid", required = false) String postid, TblXdLjzyjl tblXdLjzyjl, Model model, HttpServletRequest request) {
		int hours = new Date().getHours();
		if(hours >= 8 &&  hours < 19) {
			tblXdLjzyjl.setShift("2");
		}else {
			tblXdLjzyjl.setShift("1");
		}
		// 获取当前时间
		LocalDateTime now = LocalDateTime.now();
		logger.info("Received userid:\"!!!!!!!!!!!!!!!!!!!!!!!!!\"+\"______\"+ " + userid);

		// 如果 `userid` 从 URL 中传递，可以手动设置到 `tblXdLjzyjl`
		tblXdLjzyjl.setUserid(userid);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		logger.info("9999999999999999999999+_____" + userId);



		List<TblXdZxxdctzd> lineList = tblXdZxxdctzdService.selectLine1(userId); ;
		model.addAttribute("lineList", lineList);

		List<TblXdZxxdctzd> lineList2 = new ArrayList<>();
		model.addAttribute("lineListByStation", lineList2);

		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl);
		return "modules/tbl/tblXdLjzyjlList";
	}



	/**
	 * 查询列表
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:view")
	@RequestMapping(value = {"list1", ""})
	public String list1(@RequestParam(value = "userid", required = false) String userid,
					   @RequestParam(value = "postid", required = false) String postid, TblXdLjzyjl tblXdLjzyjl, Model model, HttpServletRequest request) {
		int hours = new Date().getHours();
		if(hours >= 8 &&  hours < 19) {
			tblXdLjzyjl.setShift("2");
		}else {
			tblXdLjzyjl.setShift("1");
		}
		// 获取当前时间
		LocalDateTime now = LocalDateTime.now();

		logger.info("Received userid:\"!!!!!!!!!!!!!!!!!!!!!!!!!\"+\"______\"+ " + userid);

		// 如果 `userid` 从 URL 中传递，可以手动设置到 `tblXdLjzyjl`
		tblXdLjzyjl.setUserid(userid);
		String I_IP_ADDR = request.getRemoteHost();
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);

		List<TblXdZxxdctzd> lineList = tblXdZxxdctzdService.selectLine1(userId); ;
		model.addAttribute("lineList", lineList);

		List<TblXdZxxdctzd> lineList2 = new ArrayList<>();
		model.addAttribute("lineListByStation", lineList2);

		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl);
		return "modules/tbl/tblXdLjzyjlList1";
	}
	/**
	 * 查询列表数据
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:view")
	@RequestMapping(value = "listData1")
	@ResponseBody
	public Page<TblXdLjzyjl> listData1(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		tblXdLjzyjl.setPage(new Page<>(request, response));
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		StringBuilder strWhere = new StringBuilder();
		if (tblXdLjzyjl.getStartTime() != null && tblXdLjzyjl.getEndTime() != null) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String startTime = dateFormat.format(tblXdLjzyjl.getStartTime());
			String endTime = dateFormat.format(tblXdLjzyjl.getEndTime());

			strWhere.append(" AND A.STATION_TIME BETWEEN '").append(startTime).append("' AND '").append(endTime).append("' ");

		if (tblXdLjzyjl.getStationCode() != null) {
			strWhere.append(" AND LEFT(A.LINE_CODE, 2) = '").append(tblXdLjzyjl.getStationCode()).append("' ");
		}

			tblXdLjzyjl.getSqlMap().put("extWhere", strWhere.toString());
		tblXdLjzyjl.setUserid(userId);
		Page<TblXdLjzyjl> page = tblXdLjzyjlService.findPage(tblXdLjzyjl);
		return page;
	}
		return null;
	}




	/**
	 * 查询列表数据
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<TblXdLjzyjl> listData(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request, HttpServletResponse response) throws ParseException {
//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		logger.info("9999999999999999999999+_____" + userId);
		tblXdLjzyjl.setPage(new Page<>(request, response));
		String shift = tblXdLjzyjl.getShift(); //班制
		Date stationTime = tblXdLjzyjl.getStationTime(); //日期
		if(stationTime != null) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			formatter.format(stationTime);
			Calendar cal = new GregorianCalendar();
			cal.setTime(stationTime);
			if("1".equals(shift)){
				//夜班

				cal.add(Calendar.DATE, -1);
				Date stationTimeE = cal.getTime();
				String timeEnded= null;
				String timeGte = formatter.format(stationTime);
				String timeLte = formatter.format(stationTimeE);
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				timeEnded = timeLte.substring(0, 10)+" 19:00:00";
				timeGte = timeGte.substring(0, 10)+" 08:00:00";
				timeLte = timeEnded;

				tblXdLjzyjl.setStationTime_gte(format.parse(timeLte));
				tblXdLjzyjl.setStationTime_lte(format.parse(timeGte));

			}else{

				cal.add(Calendar.DATE, 0);
				Date stationTimeE = cal.getTime();
				String timeEnded= null;
				String timeGte = formatter.format(stationTime);
				String timeLte = formatter.format(stationTimeE);
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				//白班
				timeGte = timeGte.substring(0, 10)+" 08:00:00";
				timeLte = timeGte.substring(0, 10)+" 19:00:00";
				tblXdLjzyjl.setStationTime_gte(format.parse(timeGte));
				tblXdLjzyjl.setStationTime_lte(format.parse(timeLte));
			}
if (tblXdLjzyjl.getStationCode()!=null){
	String strWhere = " AND LEFT(A.LINE_CODE,2) = '" + tblXdLjzyjl.getStationCode() + "' ";
	tblXdLjzyjl.getSqlMap().put("extWhere", strWhere);
}

			tblXdLjzyjl.setStationTime(null);
			tblXdLjzyjl.setShift(null);
			tblXdLjzyjl.setUserid(userId);

			Page<TblXdLjzyjl> page = tblXdLjzyjlService.findPage(tblXdLjzyjl);
			return page;
		}
return null;

	}

	/**
	 * 确认框
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:view")
	@RequestMapping(value = "form")
	public String form(TblXdLjzyjl tblXdLjzyjl, Model model) {
		List<TblZdJcr> jcrList = tblZdJcrService.findList(new TblZdJcr()); // 检车人
		model.addAttribute("jcrList", jcrList);
		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl);
		return "modules/tbl/tblXdLjzyjlForm";
	}
	
	/**
	 * 结束框
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:view")
	@RequestMapping(value = "form2")
	public String form2(TblXdLjzyjl tblXdLjzyjl, Model model) {
		TblXdLjzyjl tblXdLjzyjl_new = this.get(tblXdLjzyjl.getRecId(), false);
		tblXdLjzyjl_new.setPassword("");
		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl_new);
		return "modules/tbl/tblXdLjzyjlForm2";
	}

	/**
	 * 保存数据
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TblXdLjzyjl tblXdLjzyjl) {
		tblXdLjzyjlService.save(tblXdLjzyjl);
		return renderResult(Global.TRUE, text("保存列检作业记录成功！"));
	}
	
	/**
	 * 检车确认
	 * @throws SQLException 
	 * @throws JsonProcessingException 
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:edit")
	@RequestMapping(value = "updateJCR")
	@ResponseBody
	@JsonIgnore
	public HashMap<String, Object> updateJCR(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request) throws Exception {
//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
//		String userId = tblXdLjzyjlService.selectUserData(sessionId);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		String userName = tblZdWorkerdzDao.selectName1(userId);
		HashMap<String, Object> map = new HashMap<>();
		String JcrName = tblXdLjzyjlService.selectJnrName(tblXdLjzyjl.getJcrCode());
		// 获取IP地址、用户代码和用户名
		String I_IP_ADDR = request.getRemoteHost();
		logger.info("111111111111111111111111111111111111111111111111I_JCRNAME: " + JcrName+ "   "+"@@@@@@@@@@@@@@@@@@@@@@@@@I_USERNAME"+tblXdLjzyjl.getStationUsername());

		// 将传入参数放入map中
		map.put("I_LJZYBH", tblXdLjzyjl.getRecId());
		map.put("I_PASSWORD", tblXdLjzyjl.getPassword());
		map.put("I_JCRCODE", tblXdLjzyjl.getJcrCode());
		map.put("I_JCRNAME", JcrName);
		map.put("I_USERCODE", userId);
		map.put("I_USERNAME", userName);
		map.put("I_IP", I_IP_ADDR);
		map.put("I_TYPECODE", tblXdLjzyjl.getTypeCode());// 动检2列检1

		try {
			// 更新检车人信息
			tblXdLjzyjlService.updateJCR(map);
		} catch (SQLException e) {
			e.printStackTrace();
			return map;
		}

		// 调用集控接口请求现车信息
		if ("0".equals(map.get("O_FLAG").toString())) {
			long timestamp = System.currentTimeMillis();
			String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
			// SysInfo 数据
			Map<String, Object> sysInfo = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM213",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道代码"),
					Map.of("Name", "STATION_TRACK_CNAME", "DataType", "S", "Caption", "股道名称"),
					Map.of("Name", "USING_STATE", "DataType", "S", "Caption", "运用状态"),
					Map.of("Name", "LOCK_FLAG", "DataType", "S", "Caption", "锁定标记")
			);

			// BODY 表的 Rows 数据
			List<List<Object>> bodyRows = List.of(
					List.of("I", tblXdLjzyjl.getLineCode(), tblXdLjzyjl.getLine(), 1, 2)
			);
			logger.info("锁定标识为"+2+"需要锁线"+","+"LockLine is"+2);

			// 创建一个 ObjectMapper 实例
			ObjectMapper mapper = new ObjectMapper();


			// 将 Map 转换为 JSON 字符串

			// 发送请求并获取响应请求现车

			sleep(500);




			// 构建 Tables 数据
			List<Map<String, Object>> tables = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns, "Rows", bodyRows)
//				Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
			);
			String json = createJson(sysInfo, tables);
			logger.info("@@@@@@@@@@@@@@@"+json);

			String s2 = sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(), json);
			logger.info("@@@@@@@@@@@@@@@"+s2);

			/*第二次发电文*/
			long timestamp1 = System.currentTimeMillis();
			// 将时间戳转换为 Date 对象
			Date date = new Date(timestamp1);

			// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String formattedDate = sdf.format(date);
			String timestampWithLast4Millis1 = timestamp1 + String.format("%04d", timestamp % 10000);
			// SysInfo 数据
			Map<String, Object> sysInfo1 = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM233",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis1
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns1 = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATUS", "DataType", "S", "Caption", "标识"),
					Map.of("Name", "OPERATION_TIME", "DataType", "S", "Caption", "操作时间"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道号"),
					Map.of("Name", "OPERATOR_NO", "DataType", "S", "Caption", "操作人编号"),
					Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人名称"),
					Map.of("Name", "WAGON_NUM", "DataType", "S", "Caption", "车数"),
					Map.of("Name", "STATION_USER", "DataType", "S", "Caption", "车站调度"),
					Map.of("Name", "STATION_TIME", "DataType", "S", "Caption", "车站通知时间")
			);

			// BODY 表的 Rows 数据 操作标记I是开始 E是结束  标识 1是列检 2是动检
			List<List<Object>> bodyRows1 = List.of(
					List.of("I",
							1,
							formattedDate,
							tblXdLjzyjl.getLineCode(),
							userId,
							userName,
							0,
							tblXdLjzyjl.getStationUsername(),
							tblXdLjzyjl.getStationTime())
			);

			// DETAIL 表的 Columns 数据
			List<Map<String, String>> detailColumns = List.of(
					Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录编号"),
					Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号")
			);

			// DETAIL 表的 Rows 数据
			List<List<Object>> detailRows = new ArrayList<>();

			List<Map<String,String>> wagonList =  tblXdLjzyjlService.getWagonList(tblXdLjzyjl.getRecId());
			if(wagonList.size()==0){
				List<Object> newRow = new ArrayList<>();
				newRow.add("");
				newRow.add("");
				// 添加行到 detailRows 中
				detailRows.add(newRow);
			}else {
				// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
				for (int i = 0; i < wagonList.size(); i++) {
					// 创建新的行
					List<Object> newRow = new ArrayList<>();

					newRow.add(wagonList.get(i).get("recId"));
					newRow.add(wagonList.get(i).get("wagnNo"));
					// 添加行到 detailRows 中
					detailRows.add(newRow);
				}
			}

			// 构建 Tables 数据
			List<Map<String, Object>> tables1 = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns1, "Rows", bodyRows1),
					Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
			);

			String json1 = createJson(sysInfo1, tables1);
			logger.info("@@@@@@@@@@@@@@@"+json1);

			String s1 = sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(), json1);
			logger.info("@@@@@@@@@@@@@@@"+s1);

			}


		return map;
	}

	// 方法：将JSON字符串解析为List<Map<String, String>>
	public static List<Map<String, String>> parseJsonToListOfMap(String json) {
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			// 使用ObjectMapper解析JSON字符串为List<Map<String, String>>
			return objectMapper.readValue(json, new TypeReference<List<Map<String, String>>>() {});
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 检车结束
	 * @throws SQLException 
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:edit")
	@RequestMapping(value = "updateJCROver")
	@ResponseBody
	public HashMap<String, Object> updateJCROver(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request) throws Exception {
//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
//		String userId = tblXdLjzyjlService.selectUserData(sessionId);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		String userName = tblZdWorkerdzDao.selectName1(userId);
		HashMap<String, Object> map = new HashMap<>();
		String I_IP_ADDR = request.getRemoteHost(); // 取IP
		map.put("I_LJZYBH", tblXdLjzyjl.getRecId()); 	// 列检记录编号 传入的REC_ID
		map.put("I_PASSWORD", tblXdLjzyjl.getPassword());	// 口令
		map.put("I_USERCODE", userId); // 登录人用户编号
		map.put("I_USERNAME", userName); // 登录用户名称
		map.put("I_IP", I_IP_ADDR); // 本机IP地址
		map.put("I_TYPECODE", tblXdLjzyjl.getTypeCode());// 动检2列检1

		try {
			tblXdLjzyjlService.updateJCROver(map);
		} catch (SQLException e) {
			return map;
		}

		// 给集控系统端发数据消息
		String flag2 = map.get("O_FLAG").toString();
		if (flag2.equals("0")) {

			long timestamp = System.currentTimeMillis();
			String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
			// SysInfo 数据
			Map<String, Object> sysInfo = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM213",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道代码"),
					Map.of("Name", "STATION_TRACK_CNAME", "DataType", "S", "Caption", "股道名称"),
					Map.of("Name", "USING_STATE", "DataType", "S", "Caption", "运用状态"),
					Map.of("Name", "LOCK_FLAG", "DataType", "S", "Caption", "锁定标记")
			);

			// BODY 表的 Rows 数据
			List<List<Object>> bodyRows = List.of(
					List.of("E", tblXdLjzyjl.getLineCode(), tblXdLjzyjl.getLine(), 1, 0)
			);
			// 构建 Tables 数据
			List<Map<String, Object>> tables = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns, "Rows", bodyRows)
			);



			String json = createJson(sysInfo, tables);
			logger.info("@@@@@@@@@@@@@@@"+json);


			sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json);

			/*第二次发电文*/
			long timestamp1 = System.currentTimeMillis();
			String timestampWithLast4Millis1 = timestamp1 + String.format("%04d", timestamp % 10000);
			Date date = new Date(timestamp1);

			// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String formattedDate = sdf.format(date);
			// SysInfo 数据
			Map<String, Object> sysInfo1 = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM233",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis1
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns1 = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATUS", "DataType", "S", "Caption", "标识"),
					Map.of("Name", "OPERATION_TIME", "DataType", "S", "Caption", "操作时间"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道号"),
					Map.of("Name", "OPERATOR_NO", "DataType", "S", "Caption", "操作人编号"),
					Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人名称"),
					Map.of("Name", "WAGON_NUM", "DataType", "S", "Caption", "车数"),
					Map.of("Name", "STATION_USER", "DataType", "S", "Caption", "车站调度"),
					Map.of("Name", "STATION_TIME", "DataType", "S", "Caption", "车站通知时间")
			);

			// BODY 表的 Rows 数据 操作标记I是开始 E是结束  标识 1是列检 2是动检
			List<List<Object>> bodyRows1 = List.of(
					List.of("E",
							1,
							formattedDate,
							tblXdLjzyjl.getLineCode(),
							userId,
							userName,
							0,
							tblXdLjzyjl.getStationUsername(),
							tblXdLjzyjl.getStationTime() )
			);

			// DETAIL 表的 Columns 数据
			List<Map<String, String>> detailColumns = List.of(
					Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录编号"),
					Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号")
			);

			// DETAIL 表的 Rows 数据
			List<List<Object>> detailRows = new ArrayList<>();

			List<Map<String,String>> wagonList =  tblXdLjzyjlService.getWagonList(tblXdLjzyjl.getRecId());

			// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
			if(wagonList.size()==0){
				List<Object> newRow = new ArrayList<>();
				newRow.add("");
				newRow.add("");
				// 添加行到 detailRows 中
				detailRows.add(newRow);
			}else {
				// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
				for (int i = 0; i < wagonList.size(); i++) {
					// 创建新的行
					List<Object> newRow = new ArrayList<>();

					newRow.add(wagonList.get(i).get("recId"));
					newRow.add(wagonList.get(i).get("wagnNo"));
					// 添加行到 detailRows 中
					detailRows.add(newRow);
				}
			}

			// 构建 Tables 数据
			List<Map<String, Object>> tables1 = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns1, "Rows", bodyRows1),
					Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
			);



			String json1 = createJson(sysInfo1, tables1);
			logger.info("@@@@@@@@@@@@@@@"+json1);


			sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json1);
		}

		return map;
	}
	
	/**
	 * 取消
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:edit")
	@RequestMapping(value = "cancel")
	@ResponseBody
	public String cancel(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request) throws Exception {
//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
//		String userId = tblXdLjzyjlService.selectUserData(sessionId);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		logger.info("9999999999999999999999+_____" + userId);
		String userName = tblZdWorkerdzDao.selectName1(userId);
		HashMap<String, Object> map = new HashMap<>();
		String I_IP_ADDR = request.getRemoteHost(); // 取IP
		String I_USERCODE = UserUtils.getUser().getUserCode(); // 取用户id
		String I_USERNAME = UserUtils.getUser().getUserName(); //用户名

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		map.put("I_LJZYBH", tblXdLjzyjl.getRecId()); 	// 列检记录编号 传入的REC_ID
		map.put("I_TIME", format.format(new Date()));	// 口令
		map.put("I_USERCODE", userId); // 登录人用户编号
		map.put("I_USERNAME", userName); // 登录用户名称
		map.put("I_IP", I_IP_ADDR);// 本机IP地址
		map.put("I_TYPECODE", tblXdLjzyjl.getTypeCode());// 动检2列检1
		 try {
			tblXdLjzyjlService.cancel(map);
		} catch (SQLException e) {
			return renderResult(Global.FALSE, text("取消失败！"));
		}


		long timestamp = System.currentTimeMillis();
		String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
		// SysInfo 数据
		Map<String, Object> sysInfo = Map.of(
				"Flag", 0,
				"Msg", "",
				"SvcName", "NEM213",
				"Sender", "NE",
				"UUID", timestampWithLast4Millis
		);

		// BODY 表的 Columns 数据
		List<Map<String, String>> bodyColumns = List.of(
				Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
				Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道代码"),
				Map.of("Name", "STATION_TRACK_CNAME", "DataType", "S", "Caption", "股道名称"),
				Map.of("Name", "USING_STATE", "DataType", "S", "Caption", "运用状态"),
				Map.of("Name", "LOCK_FLAG", "DataType", "S", "Caption", "锁定标记")
		);

		// BODY 表的 Rows 数据
		List<List<Object>> bodyRows = List.of(
				List.of("I", tblXdLjzyjl.getLineCode(), tblXdLjzyjl.getLine(), 1, 0)
		);

		logger.info("锁定标识为"+0+"需要解除锁线"+","+"LockLine is"+0);

		// 构建 Tables 数据
		List<Map<String, Object>> tables = List.of(
				Map.of("Name", "BODY", "Columns", bodyColumns, "Rows", bodyRows)
//				Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
		);


		String json = createJson(sysInfo, tables);


        logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+json);

		sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json);


		/*第二次发电文*/
		long timestamp1 = System.currentTimeMillis();
		String timestampWithLast4Millis1 = timestamp1 + String.format("%04d", timestamp % 10000);
		Date date = new Date(timestamp1);

		// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedDate = sdf.format(date);
		// SysInfo 数据
		Map<String, Object> sysInfo1 = Map.of(
				"Flag", 0,
				"Msg", "",
				"SvcName", "NEM233",
				"Sender", "NE",
				"UUID", timestampWithLast4Millis1
		);

		// BODY 表的 Columns 数据
		List<Map<String, String>> bodyColumns1 = List.of(
				Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
				Map.of("Name", "STATUS", "DataType", "S", "Caption", "标识"),
				Map.of("Name", "OPERATION_TIME", "DataType", "S", "Caption", "操作时间"),
				Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道号"),
				Map.of("Name", "OPERATOR_NO", "DataType", "S", "Caption", "操作人编号"),
				Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人名称"),
				Map.of("Name", "WAGON_NUM", "DataType", "S", "Caption", "车数"),
				Map.of("Name", "STATION_USER", "DataType", "S", "Caption", "车站调度"),
				Map.of("Name", "STATION_TIME", "DataType", "S", "Caption", "车站通知时间")
		);

		// BODY 表的 Rows 数据 操作标记I是开始 E是结束  标识 1是列检 2是动检
		List<List<Object>> bodyRows1 = List.of(
				List.of("E",
						1,
						formattedDate,
						tblXdLjzyjl.getLineCode(),
						userId,
						userName,
						0,
						tblXdLjzyjl.getStationUsername(),
						tblXdLjzyjl.getStationTime() )
		);

		// DETAIL 表的 Columns 数据
		List<Map<String, String>> detailColumns = List.of(
				Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录编号"),
				Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号")
		);

		// DETAIL 表的 Rows 数据
		List<List<Object>> detailRows = new ArrayList<>();

		List<Map<String,String>> wagonList =  tblXdLjzyjlService.getWagonList(tblXdLjzyjl.getRecId());

		// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
		if(wagonList.size()==0){
			List<Object> newRow = new ArrayList<>();
			newRow.add("");
			newRow.add("");
			// 添加行到 detailRows 中
			detailRows.add(newRow);
		}else {
			// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
			for (int i = 0; i < wagonList.size(); i++) {
				// 创建新的行
				List<Object> newRow = new ArrayList<>();

				newRow.add(wagonList.get(i).get("recId"));
				newRow.add(wagonList.get(i).get("wagnNo"));
				// 添加行到 detailRows 中
				detailRows.add(newRow);
			}
		}

		// 构建 Tables 数据
		List<Map<String, Object>> tables1 = List.of(
				Map.of("Name", "BODY", "Columns", bodyColumns1, "Rows", bodyRows1),
				Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
		);



		String json1 = createJson(sysInfo1, tables1);
		logger.info("@@@@@@@@@@@@@@@"+json1);


		sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json1);
        return renderResult(Global.TRUE, text("取消成功！"));
	}
	
	/**
	 * 删除数据
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TblXdLjzyjl tblXdLjzyjl) {
		try {
			tblXdLjzyjlService.delete(tblXdLjzyjl);
			return renderResult(Global.TRUE, text("删除列检作业记录成功！"));
		} catch (Exception e) {
			return renderResult(Global.FALSE, text("删除列检作业记录失败！"));
		}
	}

	/*通知列检  M2NE43*/

	@CrossOrigin(origins = "http://172.16.16.129:5080")  // 允许的请求来源
	@PostMapping("/receiveData")
	public ResponseEntity<String> receiveData(@RequestBody JSONObject json) throws Exception {
			// 打印接收到的 JSON 数据
			logger.info("Received JSON: " + json.toJSONString());
			tblXdLjzyjlService.receiveData(json);
			// 返回接收到的数据
		return ResponseEntity.ok("success");
	}

}